import unittest
from unittest.mock import MagicMock

class StudentInfo:
    def get_info(id):
        pass

students = {
    1001:{"name":"方鸿新","age":21,"sex":"男"},
    1002:{"name":"苏文芷","age":21,"sex":"女"},
    1003:{"name":"唐晓芙","age":17,"sex":"女"}
}

# mock获取学生信息方法
def mock_get_info(id):
    return students[id]

student_info = StudentInfo()
# 使用MagicMock类实现获取学生信息对象
student_info.get_info = MagicMock(side_effect=mock_get_info)

class TestGetStudentInfo(unittest.TestCase):
    def test_mock_1(self):
        self.assertEqual({"name":"方鸿新","age":21,"sex":"男"}, student_info.get_info(1001))

    def test_mock_2(self):
        with self.assertRaises(KeyError):
            student_info.get_info(2)

if __name__ == '__main__':
    suit = unittest.TestLoader().loadTestsFromTestCase(TestGetStudentInfo)
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suit)

